﻿//驳回按钮
function overruleBtn() {
    debugger;
    //订单状态
    var status = Xrm.Page.getAttribute("new_status").getValue();
    if (status == null) {
        Xrm.Utility.alertDialog("订单状态不能空,请联系管理员！");
        return;
    } else if (status != 100000006 && status != 100000003) {
        Xrm.Utility.alertDialog("该状态下不允许驳回, 请联系管理员！");
        return;
    }
    //订单区域
    var quyu = Xrm.Page.getAttribute("new_quyu").getValue();
    var processresult = null;
    if (quyu == null) {
        Xrm.Utility.alertDialog("订单区域为空,请联系管理员！");
        return;
    } else {
        processresult = GetsalesorderapprovalprocessInfo(quyu);
        if (processresult == null) {
            Xrm.Utility.alertDialog("未找到符合条件的审批流程, 请联系管理员！");
            return;
        } 
    }
    var entityid = Xrm.Page.data.entity.getId();
    var userId = Xrm.Page.context.getUserId();
    var arrayresult = false;
    if (status == 100000006) {
        var history = GetsalesorderapprovalhistoryInfo(entityid);
        if (history == null) {
            Xrm.Utility.alertDialog("审批历史记录下级审核人为空,不能驳回,请联系管理员！");
            return;
        } else {
            debugger;
            var showRoles = ["系统管理员", "系统定制员"];
            //for (var i = 0; i < userrolesId; i++) {
            //    var rolenameresult = GetRoleName(userrolesId[i]);
            //    if (rolenameresult == null) {
            //        Xrm.Utility.alertDialog("当前用户没有安全角色，请联系管理员！");
            //        return;
            //    } else {

            //    }
            //}

            var arrayresult = isInArray(showRoles);
            if (arrayresult == false) {
                if (history[0].attributes.new_nexthandler.id.replace("{", "").replace("}", "").toUpperCase() != userId.replace("{", "").replace("}", "").toUpperCase()) {
                    Xrm.Utility.alertDialog("缺少驳回权限，请联系管理员！");
                    return;
                }
            }
        }
    } else if (status == 100000003)
    {
        var returnFlag = overruleBtn_OnClick2(processresult);
        if (!returnFlag) {
            Xrm.Utility.alertDialog("缺少驳回权限，请联系管理员！");
            return;
        }
    }

    var vaildcode = prompt("请输入驳回原因");
    if (isEmpty(vaildcode) == false) {
        Xrm.Page.data.save().then(function () {
            Xrm.Page.getAttribute("new_overrulestatus").setValue(true);
            Xrm.Page.getAttribute("new_overrulereason").setValue(vaildcode);
            if (status == 100000006) {
                Xrm.Page.getAttribute("new_status").setValue(100000003);
            } else if (status == 100000003){
                Xrm.Page.getAttribute("new_status").setValue(100000000);
            }
            Xrm.Page.getAttribute("new_overrulestatus").setValue(true);
            Xrm.Page.getAttribute("new_processnotes").setValue(null);
            Xrm.Utility.alertDialog("驳回成功！");
            Xrm.Page.data.entity.save();
        }, function () {
            Xrm.Page.getAttribute("new_overrulestatus").setValue(false);
            if (status == 100000006) {
                Xrm.Page.getAttribute("new_status").setValue(100000006);
            } else if (status == 100000003) {
                Xrm.Page.getAttribute("new_status").setValue(100000003);
            }
        });
    } else {
        Xrm.Utility.alertDialog("驳回原因不能空！");
    }
      



    //var entityid = Xrm.Page.data.entity.getId();
    //var userId = Xrm.Page.context.getUserId();
    //var vaildcode = prompt("请输入驳回原因");
    //if (vaildcode != null) {
    //    Xrm.Page.getAttribute("new_status").setValue(100000000);
    //    Xrm.Page.getAttribute("new_overrulestatus").setValue(true);



    //    Xrm.Page.data.save().then(function () {
    //        Xrm.Page.getAttribute("new_processnotes").setValue(null);
    //        Xrm.Utility.alertDialog("驳回成功！");
          

    //        var entityobj = {};
    //        //entityobj.ws_sendnumber = accountEntity.telephone1;
    //        entityobj.new_salesorder = entityid.replace("{", "").replace("}", "").toUpperCase();
    //        entityobj.new_status = 100000001;
    //        entityobj.new_approvalnode = 100000005;
    //        entityobj.new_handler = userId.replace("{", "").replace("}", "").toUpperCase();
    //        var myDate = new Date();
           
    //        entityobj.new_handletime = myDate.toLocaleDateString(); //获取当前日期
    //        entityobj.new_opinion = vaildcode;

    //        XrmServiceToolkit.Soap.createRecord("new_salesorderapprovalhistory", entityobj).then(function success(result) {
              
    //        }, function (error) {
    //            Xrm.Utility.alertDialog(error.message);
    //        });



    //        var request = {
    //            entityName: "new_salesorderapprovalhistory",
    //            entity: entityobj
    //        };
    //        XrmServiceToolkit.Soap.Create(request)
    //            .then(function (resp) {

    //            }).catch(function (error) {
    //                Xrm.Utility.alertDialog("发生错误" + error);
    //            });
          
    //    }, null);
    //}
}

/**
 * 20201020 added
 * 驳回按钮在订单状态为【正式】时逻辑
 * */
function overruleBtn_OnClick2(processresult) {
    if (processresult != null)
    {
        var processresultItem = processresult[0]["attributes"];
        var handler1 = processresultItem["new_handler1"] == undefined ? null : processresultItem["new_handler1"].id.toUpperCase();
        var handler2 = processresultItem["new_handler2"] == undefined ? null : processresultItem["new_handler2"].id.toUpperCase();
        var contextUserid = Xrm.Page.context.getUserId().replace("{","").replace("}","").toUpperCase();
        var createBy = Xrm.Page.getAttribute("createdby").getValue()[0].id.replace("{", "").replace("}", "").toUpperCase();
        if (handler1 != contextUserid)
        {
            if (handler2 == contextUserid)
            {
                if (handler1 == createBy)
                {
                    return true;
                } else
                {
                    return false;
                }
            } else
            {
                return false;
            }

        } else
        {
            if (contextUserid == createBy) {
                return false;
            } else {
                return true;
            }
        }
    }
}

/**
 * 20201020 added
 * 按钮显示隐藏
 */
function overruleBtn_DisplayRule() {
    //订单状态
    var status = Xrm.Page.getAttribute("new_status").getValue();
    //【审核中】、【正式】显示驳回按钮，否则隐藏
    if (status == 100000006 || status == 100000003)
    {
        return true;
    } else
    {
        return false;
    }
}

function isInArray(showRoles) {
    var risvisiable = false;
    var sisvisiable = false;
    var roleNames = XrmServiceToolkit.Soap.GetCurrentUserRoles();
    if (roleNames && roleNames.length > 0) {
        for (var i = 0; i < roleNames.length; i++) {
            for (var j = 0; j < showRoles.length; j++) {
                if (roleNames[i] == showRoles[j]) {
                    risvisiable = risvisiable || true;
                    break;
                } else {
                    risvisiable = risvisiable || false;
                    continue;
                }
            }
            if (risvisiable) break;
        }
    } else {
        risvisiable = risvisiable || false;
    }
    return risvisiable;
    //for (var i = 0; i < arr.length; i++) {
    //    if (value === arr[i]) {
    //        return true;
    //    }
    //}
    //return false;
}


//判断字符是否为空的方法
function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true;
    } else if (obj.match(/^[]*$/)) {
        return true;
    } else {
        return false;
    }
}


function GetRoleName(userroleid) {
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
        "<entity name='role'>" +
        "  <attribute name='name'/>" +
        "  <filter>" +
        "    <condition attribute='roleid' operator='eq' value='" + userroleid+"'/>" +
        "  </filter>" +
        "</entity>" +
        "</fetch>";
    var retrTotalQuota = XrmServiceToolkit.Soap.Fetch(fetchXml);
    if (retrTotalQuota && retrTotalQuota.length > 0) {
        return retrTotalQuota;
    }
    return null;
}


function GetsalesorderapprovalprocessInfo(territory) {
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
        "<entity name='new_salesorderapprovalprocess'>" +
        "    <all-attributes />" +
        "    <order attribute='createdon' descending='true'/>" +
        "    <filter type='and'>" +
        "        <condition attribute='statecode' operator='eq' value='0'/>" +
        "        <condition attribute='new_territory' operator='eq' value='" + territory + "'/>" +
        "        <condition attribute='statuscode' operator='eq' value='1' />" +
        "    </filter>" +
        "</entity>" +
        "</fetch>";
    var retrTotalQuota = XrmServiceToolkit.Soap.Fetch(fetchXml);
    if (retrTotalQuota && retrTotalQuota.length > 0) {
        return retrTotalQuota;
    }
    return null;
}




function GetsalesorderapprovalhistoryInfo(salesorderid) {
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
        "<entity name='new_salesorderapprovalhistory' > " +
        "   <attribute name='new_approvalnode'/>" +
        "   <attribute name='new_nexthandler'/>" +
        "  <attribute name='new_salesorderapprovalhistoryid'/>" +
        "   <order attribute='createdon' descending='true'/>" +
        "   <filter type='and'>" +
        "       <condition attribute='statecode' operator='eq' value='0'/>" +
        "       <condition attribute='new_salesorder' operator='eq' uiname='test1' uitype='salesorder' value='" + salesorderid + "'/>" +
        "   </filter>" +
        " </entity>" +
        " </fetch>";
    var retrTotalQuota = XrmServiceToolkit.Soap.Fetch(fetchXml);
    if (retrTotalQuota && retrTotalQuota.length > 0) {
        return retrTotalQuota;
    }
    return null;
}